package codingforgreat.lchot150;

public class Lc002 {
 public class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int t = 0;
        int r = 0;
        ListNode res1 = l1;
        ListNode res2 = l2;
        ListNode r1 = null;
        ListNode r2 = null;
        boolean isl1 = false;
        while(l1 != null || l2 != null){
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            r = a + b + t;
            if(r >= 10){
                r -= 10;
                t = 1;
            }else{
                t = 0;
            }
            if(l1 != null){
                isl1 = true;
                l1.val = r;
            }
            if(l2 != null){
                isl1 = false;
                l2.val = r;
            }
            r1 = l1;
            l1 = l1 == null ? null : l1.next;
            r2 = l2;
            l2 = l2 == null ? null : l2.next;
        }
        if(t != 0){
            if(isl1){
                r1.next = new ListNode(t);
            }else{
                r2.next = new ListNode(t);
            }
        }
        return isl1 ? res1 : res2;
    }
}
